package com.webchat.pgc.repository.dao.mall;

import com.webchat.domain.dto.mall.SkuShopDTO;
import com.webchat.domain.dto.mall.SkuShopInter;
import com.webchat.pgc.repository.entity.mall.MallImage;
import com.webchat.pgc.repository.entity.mall.MallSKU;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Repository
public interface IMallSKUDAO extends JpaRepository<MallSKU, Long> {

    @Query(value = "select sku.id from MallSKU sku where sku.spuId = :spuId")
    List<Long> findBySpuId(Long spuId);

    /**
     * 查询商品SPU下的所有SKU集合
     * @param spuId
     * @return
     */
    List<MallSKU> findAllBySpuId(Long spuId);

    @Transactional
    @Modifying
    @Query(value = "update MallSKU sku set sku.stock = sku.stock + :changeStock where sku.id = :skuId")
    int updateSkuStock(Long skuId, Integer changeStock);

    @Query(value = "select new com.webchat.domain.dto.mall.SkuShopDTO(sku.id, shop.id) " +
            "from MallSKU sku " +
            "left join MallSPU spu on sku.spuId = spu.id " +
            "left join MallShop shop on spu.shopId = shop.id " +
            "where sku.id in :skuIds")
    List<SkuShopDTO> querySkuShopId(List<Long> skuIds);

    /**
     * 针对原生sql且结果集来自不同entity，可以使用inerface的方式通过getXX()来接受字段
     * 如果使用JPA特性，可以使用自定以对应构造器的方式来接受查询结果（例如：querySkuShopId）
     *
     * @param skuIds
     * @return
     */
    @Query(nativeQuery = true,
           value = "select sku.id skuId, shop.id shopId " +
            "from web_chat_mall_sku sku " +
            "left join web_chat_mall_spu spu on sku.spu_id = spu.id " +
            "left join web_chat_mall_shop shop on spu.shop_id = shop.id " +
            "where sku.id in :skuIds")
    List<SkuShopInter> querySkuShopIdFromNativeSQL(List<Long> skuIds);
}
